package com.jt.www.job.messageinfotask;

import com.jt.www.common.service.MessageConsumeService;
import com.jt.www.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

/**
 * 检查消息消费定时任务
 *
 * @author admin_ltf
 * @create 2019-04-13 15:51
 */
@Component
@EnableScheduling
public class CheckMessageConsumeFailTask implements SchedulingConfigurer {

    public static final Logger log = LoggerFactory.getLogger(CheckMessageConsumeFailTask.class);
    /**
     * 单个服务器出单查询缓存失效时间 因不同的定时任务决定
     */
    private static final long MESSAGE_TIME_OUT = 80L;
    /**
     * 检查消息消费定时任务 缓存key
     */
    private static final String MESSAGE_LOCK_KEY = "EDU_MESSAGE";
    @Autowired
    MessageConsumeService messageConsumeService;
    /**
     * 任务开关
     */
    @Value("${jtpf.message.open}")
    private int checkOpen;
    /**
     * 任务执行周期
     */
    @Value("${jtpf.message.cron}")
    private String cron;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        if (checkOpen != 1) {
            return;
        }
        if (RedisUtil.setLock(MESSAGE_LOCK_KEY, "1", MESSAGE_TIME_OUT)) {
            Runnable task0 = () -> messageConsumeService.start();
            Trigger trigger0 = triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext);
            taskRegistrar.addTriggerTask(task0, trigger0);
        }
    }

}
